package com.castle.fortress.admin.cms.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.castle.fortress.admin.cms.dto.CmsArticleDto;
import com.castle.fortress.admin.cms.entity.CmsArticleEntity;
import com.castle.fortress.admin.cms.entity.CmsChannelEntity;
import com.castle.fortress.admin.cms.service.*;
import com.castle.fortress.admin.core.constants.GlobalConstants;
import com.castle.fortress.admin.system.entity.SysRole;
import com.castle.fortress.admin.system.entity.SysUser;
import com.castle.fortress.admin.utils.ExcelUtils;
import com.castle.fortress.admin.utils.WebUtil;
import com.castle.fortress.common.entity.DynamicExcelEntity;
import com.castle.fortress.common.entity.RespBody;
import com.castle.fortress.common.enums.YesNoEnum;
import com.castle.fortress.common.exception.BizException;
import com.castle.fortress.common.respcode.GlobalRespCode;
import com.castle.fortress.common.utils.ConvertUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * cms内容管理表 控制器
 *
 * @author castle
 * @since 2022-03-10
 */
@Api(tags="cms内容管理表管理控制器")
@Controller
public class CmsArticleController {
	@Autowired
	private CmsArticleService cmsArticleService;
	@Autowired
	private CmsModelDataService cmsModelDataService;
	@Autowired
	private CmsChannelService cmsChannelService;
	@Autowired
	private CmsArticleTagsService cmsArticleTagsService;
	@Autowired
	private CmsArticleSubjectService cmsArticleSubjectService;
	/**
	 * cms内容管理表的分页展示
	 * @param cmsArticleDto cms内容管理表实体类
	 * @param current 当前页
	 * @param size  每页记录数
	 * @return
	 */
	@ApiOperation("cms内容管理表分页展示")
	@GetMapping("/cms/cmsArticle/page")
	@ResponseBody
	@RequiresPermissions("cms:cmsArticle:pageList")
	public RespBody<IPage<CmsArticleDto>> pageCmsArticle(CmsArticleDto cmsArticleDto, @RequestParam(required = false) Integer current, @RequestParam(required = false)Integer size){
		Integer pageIndex= current==null? GlobalConstants.DEFAULT_PAGE_INDEX:current;
		Integer pageSize= size==null? GlobalConstants.DEFAULT_PAGE_SIZE:size;
		Page<CmsArticleDto> page = new Page(pageIndex, pageSize);
		SysUser user = WebUtil.currentUser();
		if(user==null){
			return RespBody.data(new Page(page.getCurrent(), page.getSize(),0));
		}
		if(cmsArticleDto.getIsDeleted() ==null){
			cmsArticleDto.setIsDeleted(YesNoEnum.NO.getCode());
		}
		List<Long> roldIds= null;
		//管理员和超管查看所有数据
		if(!user.getIsAdmin()&&!user.getIsSuperAdmin()){
			roldIds = new ArrayList<>();
			//非管理员用户只能查看授权的栏目及子集栏目
			List<SysRole> roles = user.getRoles();
			for(SysRole r:roles){
				roldIds.add(r.getId());
			}
			if(roldIds.isEmpty()){
				return RespBody.data(new Page(page.getCurrent(), page.getSize(),0));
			}
		}
		IPage<CmsArticleDto> pages = cmsArticleService.pageCmsArticleExtends(page, cmsArticleDto,roldIds);
		return RespBody.data(pages);
	}

	/**
	 * cms内容管理表的列表展示
	 * @param cmsArticleDto cms内容管理表实体类
	 * @return
	 */
	@ApiOperation("cms内容管理表列表展示")
	@GetMapping("/cms/cmsArticle/list")
	@ResponseBody
	public RespBody<List<CmsArticleDto>> listCmsArticle(CmsArticleDto cmsArticleDto){
		List<CmsArticleDto> list = cmsArticleService.listCmsArticle(cmsArticleDto);
		return RespBody.data(list);
	}

	/**
	 * cms内容管理表保存
	 * @param cmsArticleDto cms内容管理表实体类
	 * @return
	 */
	@ApiOperation("cms内容管理表保存")
	@PostMapping("/cms/cmsArticle/save")
	@ResponseBody
	@RequiresPermissions("cms:cmsArticle:save")
	public RespBody<String> saveCmsArticle(@RequestBody CmsArticleDto cmsArticleDto){
		if(cmsArticleDto == null ){
			throw new BizException(GlobalRespCode.PARAM_MISSED);
		}

          CmsArticleEntity cmsArticleEntity = ConvertUtil.transformObj(cmsArticleDto,CmsArticleEntity.class);
		CmsChannelEntity cmsChannelEntity = cmsChannelService.getById(cmsArticleEntity.getChannelId());
		//非草稿
		if(cmsArticleEntity.getStatus() !=0 ){
			//需要审核
			if(cmsChannelEntity.getAuditflag()){
				cmsArticleEntity.setStatus(1);
			//已发布
			}else{
				cmsArticleEntity.setStatus(2);
			}
		}
		if(cmsChannelEntity.getModel()!=null){
			cmsArticleDto.setModelId(cmsChannelEntity.getModel());
		}
		if(cmsArticleService.save(cmsArticleEntity)){
			//文章属性
			cmsArticleTagsService.updateAttrByArticle(cmsArticleEntity.getId(),cmsArticleDto.getAttr());
			//文章标签
			cmsArticleTagsService.updateTagsByArticle(cmsArticleEntity.getId(),cmsArticleDto.getTags(),"00");
			//文章专题
			List<Long> articleids = new ArrayList<>();
			articleids.add(cmsArticleEntity.getId());
			cmsArticleSubjectService.updateArtiSubBatch(articleids,cmsArticleDto.getSpecial());
			//初始化文章访问地址
			if(StrUtil.isEmpty(cmsArticleEntity.getUrl())){

				cmsArticleEntity.setUrl("/page/"+cmsChannelEntity.getCode()+"/"+cmsArticleEntity.getId());
				cmsArticleService.updateById(cmsArticleEntity);
			}
			if((cmsArticleDto.getColData()!=null && !cmsArticleDto.getColData().isEmpty()) && cmsArticleDto.getModelId()!=null){
				cmsArticleDto.getColData().put("id",cmsArticleEntity.getId());
				cmsModelDataService.saveData(cmsArticleDto.getModelId()+"",cmsArticleDto.getColData());
			}
			return RespBody.data("保存成功");
		}else{
			return RespBody.fail(GlobalRespCode.OPERATE_ERROR);
		}
	}

	/**
	 * cms内容管理表编辑
	 * @param cmsArticleDto cms内容管理表实体类
	 * @return
	 */
	@ApiOperation("cms内容管理表编辑")
	@PostMapping("/cms/cmsArticle/edit")
	@ResponseBody
	@RequiresPermissions("cms:cmsArticle:edit")
	public RespBody<String> updateCmsArticle(@RequestBody CmsArticleDto cmsArticleDto){
		if(cmsArticleDto == null || cmsArticleDto.getId() == null || cmsArticleDto.getId().equals(0L)){
			throw new BizException(GlobalRespCode.PARAM_MISSED);
		}
          CmsArticleEntity cmsArticleEntity = ConvertUtil.transformObj(cmsArticleDto,CmsArticleEntity.class);
		String regex="^/page/[0-9a-zA-Z]+/\\d+$";
		//默认的访问地址则替换成最新的渠道code
		CmsChannelEntity cmsChannelEntity = cmsChannelService.getById(cmsArticleEntity.getChannelId());
		if(StrUtil.isEmpty(cmsArticleEntity.getUrl())||cmsArticleEntity.getUrl().matches(regex)){
			cmsArticleEntity.setUrl("/page/"+cmsChannelEntity.getCode()+"/"+cmsArticleEntity.getId());
		}
		if(cmsChannelEntity.getModel()!=null){
			cmsArticleDto.setModelId(cmsChannelEntity.getModel());
		}
		//非草稿
		if(cmsArticleEntity.getStatus() !=0 ){
			//需要审核
			if(cmsChannelEntity.getAuditflag()){
				cmsArticleEntity.setStatus(1);
				//已发布
			}else{
				cmsArticleEntity.setStatus(2);
			}
		}
		if(cmsArticleService.updateById(cmsArticleEntity)){
			//文章属性
			cmsArticleTagsService.updateAttrByArticle(cmsArticleEntity.getId(),cmsArticleDto.getAttr());
			//文章标签
			cmsArticleTagsService.updateTagsByArticle(cmsArticleEntity.getId(),cmsArticleDto.getTags(),"01");
			//文章专题
			List<Long> articleids = new ArrayList<>();
			articleids.add(cmsArticleEntity.getId());
			cmsArticleSubjectService.updateArtiSubBatch(articleids,cmsArticleDto.getSpecial());
			if(cmsArticleDto.getColData()!=null && cmsArticleDto.getModelId()!=null){
				cmsArticleDto.getColData().put("id",cmsArticleEntity.getId());
				cmsModelDataService.saveData(cmsArticleDto.getModelId()+"",cmsArticleDto.getColData());
			}
			return RespBody.data("保存成功");
		}else{
			return RespBody.fail(GlobalRespCode.OPERATE_ERROR);
		}
	}

	/**
	 * cms内容管理表审核
	 * @param cmsArticleDto cms内容管理表实体类
	 * @return
	 */
	@ApiOperation("cms内容管理表审核")
	@PostMapping("/cms/cmsArticle/audit")
	@ResponseBody
	@RequiresPermissions("cms:cmsArticle:audit")
	public RespBody<String> auditCmsArticle(@RequestBody CmsArticleDto cmsArticleDto){
		if(cmsArticleDto == null || cmsArticleDto.getId() == null || cmsArticleDto.getId().equals(0L)){
			throw new BizException(GlobalRespCode.PARAM_MISSED);
		}
		SysUser user = WebUtil.currentUser();
		CmsArticleEntity cmsArticleEntity = ConvertUtil.transformObj(cmsArticleDto,CmsArticleEntity.class);
		//只沉淀审核状态和意见
		if(cmsArticleEntity.getStatus()!=2 && cmsArticleEntity.getStatus()!=3){
			cmsArticleEntity.setStatus(1);
		}
		CmsArticleEntity entity = new CmsArticleEntity();
		entity.setId(cmsArticleEntity.getId());
		entity.setStatus(cmsArticleEntity.getStatus());
		entity.setAuditer(user.getId());
		entity.setAuditdate(new Date());
		entity.setAuditop(cmsArticleEntity.getAuditop());
		if(cmsArticleService.updateById(entity)){
			return RespBody.data("保存成功");
		}else{
			return RespBody.fail(GlobalRespCode.OPERATE_ERROR);
		}
	}


	/**
	 * 可审核文章分页展示
	 * @param cmsArticleDto cms内容管理表实体类
	 * @param current 当前页
	 * @param size  每页记录数
	 * @return
	 */
	//TODO 待测试
	@ApiOperation("可审核文章分页展示")
	@GetMapping("/cms/cmsArticle/pageaudit")
	@ResponseBody
	@RequiresPermissions("cms:cmsArticle:audit")
	public RespBody<IPage<CmsArticleDto>> pageAudit(CmsArticleDto cmsArticleDto, @RequestParam(required = false) Integer current, @RequestParam(required = false)Integer size){
		Integer pageIndex= current==null? GlobalConstants.DEFAULT_PAGE_INDEX:current;
		Integer pageSize= size==null? GlobalConstants.DEFAULT_PAGE_SIZE:size;
		Page<CmsArticleDto> page = new Page(pageIndex, pageSize);
		SysUser user = WebUtil.currentUser();
		IPage<CmsArticleDto> pages = cmsArticleService.pageAudit(page, cmsArticleDto,user);
		return RespBody.data(pages);
	}



	/**
	 * cms内容管理表删除
	 * @param id
	 * @return
	 */
	@ApiOperation("cms内容管理表删除")
	@PostMapping("/cms/cmsArticle/delete")
	@ResponseBody
	@RequiresPermissions("cms:cmsArticle:delete")
	public RespBody<String> deleteCmsArticle(@RequestParam Long id){
		if(id == null ){
			throw new BizException(GlobalRespCode.PARAM_MISSED);
		}
		if(cmsArticleService.removeById(id)) {
			return RespBody.data("保存成功");
		}else{
			return RespBody.fail(GlobalRespCode.OPERATE_ERROR);
		}
	}

	/**
	 * cms内容移动到草稿箱
	 * @param ids
	 * @return
	 */
	@ApiOperation("cms内容移动到草稿箱")
	@PostMapping("/cms/cmsArticle/toDrafts")
	@ResponseBody
	@RequiresPermissions("cms:cmsArticle:toDrafts")
	public RespBody<String> toDrafts(@RequestBody List<Long> ids){
		if(ids == null || ids.size()<1){
			throw new BizException(GlobalRespCode.PARAM_MISSED);
		}
		if(cmsArticleService.toDrafts(ids)) {
			return RespBody.data("保存成功");
		}else{
			return RespBody.fail(GlobalRespCode.OPERATE_ERROR);
		}
	}

	/**
	 * cms内容彻底删除
	 * @param ids
	 * @return
	 */
	@ApiOperation("cms内容彻底删除")
	@PostMapping("/cms/cmsArticle/toDelReal")
	@ResponseBody
	@RequiresPermissions("cms:cmsArticle:toDelReal")
	public RespBody<String> toDelReal(@RequestBody List<Long> ids){
		if(ids == null || ids.size()<1){
			throw new BizException(GlobalRespCode.PARAM_MISSED);
		}
		if(cmsArticleService.toDelReal(ids)) {
			return RespBody.data("保存成功");
		}else{
			return RespBody.fail(GlobalRespCode.OPERATE_ERROR);
		}
	}


	/**
	 * cms内容移动到回收站
	 * @param ids
	 * @return
	 */
	@ApiOperation("cms内容移动到回收站")
	@PostMapping("/cms/cmsArticle/toGarbage")
	@ResponseBody
	@RequiresPermissions("cms:cmsArticle:toGarbage")
	public RespBody<String> deleteCmsArticleBatch(@RequestBody List<Long> ids){
		if(ids == null || ids.size()<1){
			throw new BizException(GlobalRespCode.PARAM_MISSED);
		}
		if(cmsArticleService.toGarbage(ids)) {
			return RespBody.data("保存成功");
		}else{
			return RespBody.fail(GlobalRespCode.OPERATE_ERROR);
		}
	}


	/**
	 * 批量移动文章栏目
	 * @param map
	 * @return
	 */
	@ApiOperation("批量移动文章栏目")
	@PostMapping("/cms/cmsArticle/moveChannel")
	@ResponseBody
	@RequiresPermissions("cms:cmsArticle:moveChannel")
	public RespBody<String> moveChannel(@RequestBody Map<String,Object> map){
		if(map == null || map.get("ids") == null || map.get("channelId") == null){
			throw new BizException(GlobalRespCode.PARAM_MISSED);
		}
		try {
			List<Long> ids = (List<Long>)map.get("ids");
			Long channelId = Long.parseLong(map.get("channelId").toString());
			if(cmsArticleService.moveChannel(ids,channelId)) {
				return RespBody.data("保存成功");
			}else{
				return RespBody.fail(GlobalRespCode.OPERATE_ERROR);
			}
		} catch (Exception e) {
			e.printStackTrace();
			return RespBody.fail(GlobalRespCode.OPERATE_ERROR);
		}
	}

	/**
	 * cms内容管理表详情
	 * @param id cms内容管理表id
	 * @return
	 */
	@ApiOperation("cms内容管理表详情")
	@GetMapping("/cms/cmsArticle/info")
	@ResponseBody
	@RequiresPermissions("cms:cmsArticle:info")
	public RespBody<CmsArticleDto> infoCmsArticle(@RequestParam Long id){
		if(id == null){
			throw new BizException(GlobalRespCode.PARAM_MISSED);
		}
        CmsArticleDto cmsArticleDto =  cmsArticleService.getByIdExtends(id);
		return RespBody.data(cmsArticleDto);
	}

	/**
     * 动态表头导出 依据展示的字段导出对应报表
     * @param dynamicExcelEntity
     * @param response
     * @throws Exception
     */
	@PostMapping("/cms/cmsArticle/exportDynamic")
	@ApiOperation("动态表头导出，依据展示的字段导出对应报表")
	public void exportDynamic(@RequestBody DynamicExcelEntity<CmsArticleDto> dynamicExcelEntity, HttpServletResponse response) throws Exception {
		List<CmsArticleDto> list = cmsArticleService.listCmsArticle(dynamicExcelEntity.getDto());
		//字典、枚举、接口、json常量等转义后的列表数据 根据实际情况初始化该对象，null为list数据直接导出
		List<List<Object>> dataList = null;
		/**
        * 根据实际情况初始化dataList,可参照 com.castle.fortress.admin.system.controller.TmpDemoController类中方法：exportDynamic
        */
		ExcelUtils.exportDynamic(response,dynamicExcelEntity.getFileName()+".xlsx",null,list,dynamicExcelEntity.getHeaderList(),dataList);
	}


}
